var request = require('request').defaults({ jar: true });
j = request.jar();

class tieba {
	constructor() {
		var args = Array.prototype.slice.call(arguments);
		if (args.length == 1) {
			j.setCookie(request.cookie(`BDUSS=${args[0]}`), 'http://tieba.baidu.com');
		} else {
			throw new Error('failed to get user information');
		}
	}
	tbs() {
		return new Promise(function(resolve, reject) {
			request({
				url: 'http://tieba.baidu.com/dc/common/tbs',
				jar: j
			}, function(err, res, body) {
				if (!err && res.statusCode == 200) {
					resolve(JSON.parse(body)["tbs"]);
				} else {
					reject(err);
				}
			})
		});
	}
	sign(bar) {
		return this.tbs().then(function(msg) {
			return new Promise(function(resolve, reject) {
				request.post({
					url: 'http://tieba.baidu.com/sign/add',
					form: {
						ie: 'utf-8',
						kw: bar,
						tbs: msg
					},
					jar: j
				}, function(err, res, body) {
					body = JSON.parse(body);
					if (!err && res.statusCode == 200) {
						if (body["no"] == 0)
							resolve(body["data"]);
						else
							reject(body["error"]);
					} else {
						reject(err);
					}
				});
			});
		});
	}
}

module.exports = tieba;
